package be.sc.classicnetwork.controller.validator;

import java.io.Serializable;

import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;
import org.hibernate.validator.Validator;

import be.sc.classicnetwork.exception.ApplicationException;

/**
 * Validator for
 * 
 * @Expression.
 */
public class ExpressionValidator implements Validator<Expression>, Serializable {

    private static final long serialVersionUID = -290876975917088346L;

    private String expression;

    public void initialize(Expression expression) {
	this.expression = expression.assertTrue();
    }

    @SuppressWarnings("unchecked")
    public boolean isValid(Object value) {
	if (value == null)
	    return true;

	try {
	    org.apache.commons.jexl.Expression e = ExpressionFactory.createExpression(expression);
	    JexlContext jc = JexlHelper.createContext();
	    jc.getVars().put("this", value);
	    return (Boolean) e.evaluate(jc);
	} catch (Exception e) {
	    throw new ApplicationException("A Problem occured while using ExpressionValidator", e);
	}
    }
}